/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormOrderPembelian.java
 *
 * Created on May 9, 2011, 10:52:12 PM
 */

package com.kifas.ui.purchase;

import com.kifas.model.xml.BarangModel;
import com.kifas.model.xml.KontrakModel;
import com.kifas.model.xml.KontrakPembelianModel;
import com.kifas.model.xml.PembelianDetailModel;
import com.kifas.model.xml.PembelianModel;
import com.kifas.model.xml.PersistStatus;
import com.kifas.model.xml.ReferenceNumberingModel;
import com.kifas.model.xml.SupplierModel;
import com.kifas.sales.ui.tablemodel.ComboBarangCellEditor;
import com.kifas.service.MasterService;
import com.kifas.service.PembelianService;
import com.kifas.ui.master.LookUpBLNumber;
import com.kifas.ui.master.LookUpKontrak;
import com.kifas.ui.master.LookUpSupplier;
import com.kifas.ui.util.TextComponentUtils;
import java.awt.Component;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.swingbinding.JComboBoxBinding;
import org.jdesktop.swingbinding.SwingBindings;

/**
 *
 * @author dhamarsu
 */
public class FormOrderPembelian extends javax.swing.JInternalFrame {
    private MasterService masterService = new MasterService();
    private PembelianService pembelianService = new PembelianService();
    private SupplierModel supplierModel;
    private List<PembelianDetailModel> detailPembelianModels;
    private PembelianModel pembelianModel;
    private KontrakModel kontrakModel;
    private KontrakPembelianModel kontrakPembelianModel;

    private List<BarangModel> barangs;
    /** Creates new form FormOrderPembelian */
    public FormOrderPembelian() {
        initComponents();

        dtOrderPembelian.setDate(new Date());

        barangs =  masterService.getBarangs();

        BindingGroup bindingGroup = new BindingGroup();

        JComboBoxBinding barangBinding =
                SwingBindings.createJComboBoxBinding(
                UpdateStrategy.READ,
                barangs,
                cboBarang);

        cboBarang.setRenderer(new DefaultListCellRenderer() {
           @Override
           public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
               super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
               if (value instanceof BarangModel) {
                   BarangModel mec = (BarangModel)value;
                   setText(mec.getKdBarang());
               }
               return this;
           }
        });
        bindingGroup.addBinding(barangBinding);
        bindingGroup.bind();

        tablePurchase.setAutoCreateColumnsFromModel(false);
        detailPembelianModels = new ArrayList<PembelianDetailModel>();
        tablePurchase.setModel(new PembelianTableModel(detailPembelianModels));
        tablePurchase.getColumnModel().getColumn(0).setCellEditor(new ComboBarangCellEditor( cboBarang));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNoOrder = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        dtOrderPembelian = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        txtSupplier = new javax.swing.JTextField();
        btnSupplier = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txtKontrak = new javax.swing.JTextField();
        btnKontrak = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        txtBLNumber = new javax.swing.JTextField();
        btnBLNumber = new javax.swing.JButton();
        rdoPajak = new javax.swing.JRadioButton();
        rdoNonPajak = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtAlamat = new javax.swing.JTextArea();
        jToolBar1 = new javax.swing.JToolBar();
        btnNew = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        btnBrowse = new javax.swing.JButton();
        btnDo = new javax.swing.JButton();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        tablePurchase = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtSubTotal = new javax.swing.JLabel();
        txtPajak = new javax.swing.JLabel();
        txtTotal = new javax.swing.JLabel();
        txtDiscount = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtKeterangan = new javax.swing.JTextArea();
        cboBarang = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setTitle("Form Order Pembelian");

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText("No Order");
        jLabel1.setName("jLabel1"); // NOI18N

        txtNoOrder.setText("AUTO");
        txtNoOrder.setName("txtNoOrder"); // NOI18N

        jLabel2.setText("Tanggal");
        jLabel2.setName("jLabel2"); // NOI18N

        dtOrderPembelian.setDateFormatString("dd/MM/yyyy"); // NOI18N
        dtOrderPembelian.setEnabled(false);
        dtOrderPembelian.setName("dtOrderPembelian"); // NOI18N

        jLabel3.setText("Supplier");
        jLabel3.setName("jLabel3"); // NOI18N

        txtSupplier.setName("txtSupplier"); // NOI18N

        btnSupplier.setText("...");
        btnSupplier.setName("btnSupplier"); // NOI18N
        btnSupplier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSupplierActionPerformed(evt);
            }
        });

        jLabel4.setText("Kontrak");
        jLabel4.setName("jLabel4"); // NOI18N

        txtKontrak.setName("txtKontrak"); // NOI18N

        btnKontrak.setText("...");
        btnKontrak.setName("btnKontrak"); // NOI18N
        btnKontrak.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnKontrakActionPerformed(evt);
            }
        });

        jLabel5.setText("BL Number");
        jLabel5.setName("jLabel5"); // NOI18N

        txtBLNumber.setName("txtBLNumber"); // NOI18N

        btnBLNumber.setText("...");
        btnBLNumber.setName("btnBLNumber"); // NOI18N
        btnBLNumber.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBLNumberActionPerformed(evt);
            }
        });

        buttonGroup1.add(rdoPajak);
        rdoPajak.setSelected(true);
        rdoPajak.setText("Pajak");
        rdoPajak.setName("rdoPajak"); // NOI18N

        buttonGroup1.add(rdoNonPajak);
        rdoNonPajak.setText("Harga Termasuk Pajak");
        rdoNonPajak.setName("rdoNonPajak"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dtOrderPembelian, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtNoOrder, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE))
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rdoPajak)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rdoNonPajak)))
                .addGap(32, 32, 32)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtBLNumber)
                    .addComponent(txtKontrak, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnKontrak, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBLNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(95, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtKontrak, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnKontrak))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtBLNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnBLNumber)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtNoOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(txtSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnSupplier))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(dtOrderPembelian, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(rdoPajak)
                                .addComponent(rdoNonPajak)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Master", jPanel1);

        jPanel2.setName("jPanel2"); // NOI18N

        jLabel6.setText("Alamat");
        jLabel6.setName("jLabel6"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtAlamat.setColumns(20);
        txtAlamat.setRows(5);
        txtAlamat.setName("txtAlamat"); // NOI18N
        jScrollPane1.setViewportView(txtAlamat);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(456, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Alamat", jPanel2);

        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N
        jToolBar1.setPreferredSize(new java.awt.Dimension(100, 30));

        btnNew.setText("New");
        btnNew.setFocusable(false);
        btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNew.setName("btnNew"); // NOI18N
        btnNew.setPreferredSize(new java.awt.Dimension(100, 29));
        btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        jToolBar1.add(btnNew);

        btnSave.setText("Save");
        btnSave.setFocusable(false);
        btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSave.setName("btnSave"); // NOI18N
        btnSave.setPreferredSize(new java.awt.Dimension(100, 29));
        btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSave);

        jButton1.setText("Cancel");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setPreferredSize(new java.awt.Dimension(100, 29));
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        btnBrowse.setText("Browse");
        btnBrowse.setFocusable(false);
        btnBrowse.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBrowse.setName("btnBrowse"); // NOI18N
        btnBrowse.setPreferredSize(new java.awt.Dimension(100, 29));
        btnBrowse.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });
        jToolBar1.add(btnBrowse);

        btnDo.setText("Print");
        btnDo.setFocusable(false);
        btnDo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDo.setName("btnDo"); // NOI18N
        btnDo.setPreferredSize(new java.awt.Dimension(100, 29));
        btnDo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDoActionPerformed(evt);
            }
        });
        jToolBar1.add(btnDo);

        jTabbedPane2.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
        jTabbedPane2.setName("jTabbedPane2"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        tablePurchase.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Kode BRG", "Nama", "Qty", "Satuan", "Harga", "Disc(%)", "Discount", "Pajak", "Sub Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                true, true, false, true, false, false, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablePurchase.setName("tablePurchase"); // NOI18N
        tablePurchase.setRowHeight(24);
        tablePurchase.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tablePurchaseKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(tablePurchase);

        jTabbedPane2.addTab("Daftar Item", jScrollPane3);

        jPanel3.setName("jPanel3"); // NOI18N

        jLabel7.setText("Sub Total");
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setText("Pajak");
        jLabel8.setName("jLabel8"); // NOI18N

        jLabel9.setText("Discount");
        jLabel9.setName("jLabel9"); // NOI18N

        jLabel10.setText("Total");
        jLabel10.setName("jLabel10"); // NOI18N

        txtSubTotal.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
        txtSubTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        txtSubTotal.setText("0");
        txtSubTotal.setName("txtSubTotal"); // NOI18N

        txtPajak.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
        txtPajak.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        txtPajak.setText("0");
        txtPajak.setName("txtPajak"); // NOI18N

        txtTotal.setFont(new java.awt.Font("DejaVu Sans", 1, 18));
        txtTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        txtTotal.setText("0");
        txtTotal.setName("txtTotal"); // NOI18N

        txtDiscount.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
        txtDiscount.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        txtDiscount.setText("0");
        txtDiscount.setName("txtDiscount"); // NOI18N

        jLabel11.setText("Keterangan");
        jLabel11.setName("jLabel11"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        txtKeterangan.setColumns(20);
        txtKeterangan.setRows(5);
        txtKeterangan.setText("-");
        txtKeterangan.setName("txtKeterangan"); // NOI18N
        jScrollPane2.setViewportView(txtKeterangan);

        cboBarang.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboBarang.setName("cboBarang"); // NOI18N
        cboBarang.setPreferredSize(new java.awt.Dimension(0, 0));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9)
                            .addComponent(jLabel7))
                        .addGap(31, 31, 31)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtSubTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                            .addComponent(txtDiscount, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                            .addComponent(txtTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                            .addComponent(txtPajak, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)))
                    .addComponent(jLabel8))
                .addGap(173, 173, 173)
                .addComponent(cboBarang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(178, 178, 178)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel9)
                                    .addComponent(txtDiscount))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel7)
                                    .addComponent(txtSubTotal))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel8)
                                    .addComponent(txtPajak))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel10)
                                    .addComponent(txtTotal)))))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(cboBarang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 927, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 903, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 903, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(28, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        // TODO add your handling code here:
        clearForm();
        txtNoOrder.setText("AUTO");
        PembelianDetailModel detailModel = new PembelianDetailModel();
        detailModel.setQty(0);
        detailModel.setPrice(new BigDecimal(0));
        detailModel.setSubTotal(new BigDecimal(0));
        detailModel.setDiscount(new BigDecimal(0));
        detailModel.setPajak(new BigDecimal(0));
        detailModel.setDiscount2(new BigDecimal(0));
        detailPembelianModels.add(detailModel);
        refreshTable();
}//GEN-LAST:event_btnNewActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        ReferenceNumberingModel rf = masterService.getReferenceNumber(2, "PO");
        
        txtNoOrder.setText(rf.getResult());
        PembelianModel pm = new PembelianModel();
        pm.setKeterangan(txtKeterangan.getText());
        pm.setKirim(false);

        if (kontrakModel != null)
            pm.setNomorKontrakPembelian(kontrakModel.getNomorKontrak());

        pm.setNomorPo(txtNoOrder.getText());

        if (rdoPajak.isSelected()){
            pm.setPajak(true);
        }else{
            pm.setPajak(false);
        }
        
        pm.setSuplier(supplierModel);
        pm.setTanggal(dtOrderPembelian.getDate());
//        pm.setTanggalJatuhTempo();

        Set<PembelianDetailModel> set = new HashSet(detailPembelianModels);
        pm.setPembelianDetailModels(set);
        try{
            PersistStatus status = pembelianService.setPembelian(pm);
            JOptionPane.showMessageDialog(null, status.getStatus());
//            if (status.getStatus().equals("success"))
//                p = pm;
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Penyimpanan gagal.");
        }
}//GEN-LAST:event_btnSaveActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        clearForm();
}//GEN-LAST:event_jButton1ActionPerformed

    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_btnBrowseActionPerformed

    private void btnDoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDoActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_btnDoActionPerformed

    private void tablePurchaseKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablePurchaseKeyPressed
        // TODO add your handling code here:
//        if (tablePurchase.getSelectedColumn() == 0 && evt.getKeyCode() == KeyEvent.VK_ENTER){
//            BarangModel barangModel = new LookUpBarang(null, closable).getBarangModel();
//            detailPembelianModels.get(tablePurchase.getSelectedRow()).setBarang(barangModel);
//            refreshTable();
//        }
}//GEN-LAST:event_tablePurchaseKeyPressed

    private void btnSupplierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSupplierActionPerformed
        // TODO add your handling code here:
        supplierModel = new LookUpSupplier(null, true).getSupplierModel();
        if(supplierModel != null){
            txtSupplier.setText(supplierModel.getNamaSupplier());
            txtAlamat.setText(supplierModel.getAlamat());
        }
    }//GEN-LAST:event_btnSupplierActionPerformed

    private void btnKontrakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKontrakActionPerformed
        // TODO add your handling code here:
        if (supplierModel == null){
            JOptionPane.showMessageDialog(this, "Pilih Supplier terlebih dahulu!",
                    "error",JOptionPane.ERROR_MESSAGE);
        }else{
            kontrakModel = new LookUpKontrak(null, true).getKontrakModel(supplierModel);
            if(kontrakModel != null)
                txtKontrak.setText(kontrakModel.getNomorKontrak());
        }
    }//GEN-LAST:event_btnKontrakActionPerformed

    private void btnBLNumberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBLNumberActionPerformed
        // TODO add your handling code here:
        if (kontrakModel == null){
            JOptionPane.showMessageDialog(this, "Pilih Kontrak terlebih dahulu!",
                    "error",JOptionPane.ERROR_MESSAGE);
        }else{
            List<KontrakPembelianModel> kontrakPembelianModels = new ArrayList<KontrakPembelianModel>(kontrakModel.getKontrakPembelians());
            kontrakPembelianModel = new LookUpBLNumber(null, true, kontrakPembelianModels).getKontrakPembelianModel(kontrakPembelianModels);
            if(kontrakPembelianModel != null)
                txtBLNumber.setText(kontrakPembelianModel.getNomorKontrakPembelian());
        }
    }//GEN-LAST:event_btnBLNumberActionPerformed


    private void refreshTable(){
        tablePurchase.setModel(new PembelianTableModel(detailPembelianModels));
    }

    private void clearForm(){
        detailPembelianModels = new ArrayList<PembelianDetailModel>();
        txtNoOrder.setText(""); txtSupplier.setText(""); txtAlamat.setText("");
        txtKontrak.setText(""); txtBLNumber.setText("");
        dtOrderPembelian.setDate(new Date());
        refreshTable();
        refreshTotalLabel();
    }

    private void refreshTotalLabel(){
        if(detailPembelianModels !=null && !detailPembelianModels.isEmpty()){
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal pajak = BigDecimal.ZERO;
            BigDecimal discount = BigDecimal.ZERO;
            for (PembelianDetailModel detailModel : detailPembelianModels) {
                total = total.add(detailModel.getSubTotal());
                pajak = pajak.add(detailModel.getPajak());
                discount = discount.add(detailModel.getDiscount());
            }
            txtSubTotal.setText(TextComponentUtils.formatNumber(total));
            txtPajak.setText(TextComponentUtils.formatNumber(pajak));
            txtDiscount.setText(TextComponentUtils.formatNumber(discount));

            txtTotal.setText(TextComponentUtils.formatNumber(total.add(pajak)));
        }else{
            txtSubTotal.setText("0");
            txtDiscount.setText("0");
            txtPajak.setText("0");
            txtTotal.setText("0");
        }
    }

    private class PembelianTableModel extends AbstractTableModel{
        private List<PembelianDetailModel> detailPembelianModels;

        public PembelianTableModel(List<PembelianDetailModel> detailPembelianModels) {
            this.detailPembelianModels = detailPembelianModels;
        }

        @Override
        public int getRowCount() {
            return detailPembelianModels.size();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
                PembelianDetailModel s = detailPembelianModels.get(rowIndex);
                if (columnIndex == 0){
                    if (s.getBarang() != null)
                        return s.getBarang().getKdBarang();
                }else if (columnIndex == 1){
                    if (s.getBarang() != null)
                        return s.getBarang().getNamaBarang();
                }else if (columnIndex == 2){
                    if (s.getQty() != null)
                        return s.getQty();
                }else if (columnIndex == 3){
                     if (s.getBarang().getSatuan() != null)
                        return s.getBarang().getSatuan().getSatuan();
                }else if (columnIndex == 4){
                     if (s.getPrice() != null)
                        return s.getPrice();
                }else if (columnIndex == 5){
                    if (s.getDiscount2() != null)
                        return s.getDiscount2();
                }else if (columnIndex == 6){
                    if (s.getDiscount() != null)
                        return s.getDiscount();
                }else if (columnIndex == 7){
                    if (s.getPajak() != null)
                        return s.getPajak();
                }else if (columnIndex == 8){
                    if (s.getSubTotal() != null)
                        return s.getSubTotal();
                }
                return "";
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            if(columnIndex == 1 || columnIndex == 10  || columnIndex == 9 || columnIndex == 8) {
                return false;
            }
            return true;
        }
        
        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            PembelianDetailModel s = detailPembelianModels.get(rowIndex);
            if (columnIndex == 0){
                s.setBarang((BarangModel) aValue);
//                s.setSatuan(s.getBarang().getSatuan());
//                s.setPrice(s.getBarang().getHargaJual());
                s.setSubTotal(s.getPrice().multiply(
                    new BigDecimal(s.getQty())).subtract(s.getDiscount2()).setScale(2));
                if(rdoPajak.isSelected())
                    s.setPajak(s.getSubTotal().multiply(new BigDecimal(0.1)));
                s.setPajak(s.getPajak().setScale(2, RoundingMode.HALF_DOWN));
            }else if(columnIndex == 2){
                s.setQty(Integer.parseInt(aValue.toString()));
                s.setSubTotal(s.getPrice().multiply(
                    new BigDecimal(s.getQty())).subtract(s.getDiscount()).setScale(2));
                if(rdoPajak.isSelected())
                    s.setPajak(s.getSubTotal().multiply(new BigDecimal(0.1)));
                s.setPajak(s.getPajak().setScale(2, RoundingMode.HALF_DOWN));
            }else if (columnIndex == 4){
                s.setPrice((BigDecimal) aValue);
                s.setSubTotal(s.getPrice().multiply(
                    new BigDecimal(s.getQty())).subtract(s.getDiscount()).setScale(2));
                if(rdoPajak.isSelected())
                    s.setPajak((s.getSubTotal().multiply(new BigDecimal(0.1))));
                s.setPajak(s.getPajak().setScale(2, RoundingMode.HALF_DOWN));
            }else if (columnIndex == 5){
                s.setDiscount2(new BigDecimal(aValue.toString()));
                s.setDiscount(s.getPrice().multiply(
                    new BigDecimal(s.getQty())).multiply(s.getDiscount2().divide(new BigDecimal(100))).setScale(2));
                s.setSubTotal(s.getPrice().multiply(
                    new BigDecimal(s.getQty())).subtract(s.getDiscount()).setScale(2));
                if(rdoPajak.isSelected())
                    s.setPajak((s.getSubTotal().multiply(new BigDecimal(0.1))));
                s.setPajak(s.getPajak().setScale(2, RoundingMode.HALF_DOWN));
            }
            refreshTable();
            refreshTotalLabel();
        }

        @Override
        public int getColumnCount() {
            return 5;
        }
        

    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBLNumber;
    private javax.swing.JButton btnBrowse;
    private javax.swing.JButton btnDo;
    private javax.swing.JButton btnKontrak;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSupplier;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cboBarang;
    private com.toedter.calendar.JDateChooser dtOrderPembelian;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JRadioButton rdoNonPajak;
    private javax.swing.JRadioButton rdoPajak;
    private javax.swing.JTable tablePurchase;
    private javax.swing.JTextArea txtAlamat;
    private javax.swing.JTextField txtBLNumber;
    private javax.swing.JLabel txtDiscount;
    private javax.swing.JTextArea txtKeterangan;
    private javax.swing.JTextField txtKontrak;
    private javax.swing.JTextField txtNoOrder;
    private javax.swing.JLabel txtPajak;
    private javax.swing.JLabel txtSubTotal;
    private javax.swing.JTextField txtSupplier;
    private javax.swing.JLabel txtTotal;
    // End of variables declaration//GEN-END:variables

}
